package com.yonyougov.devops.cruxcisupport.harbor.repositories;

import com.yonyougov.devops.cruxcisupport.harbor.utils.HarborInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Component
@Slf4j
public class HarborRepositoriesDao {
    @Autowired
    private HarborInfo harborInfo;

    /**
     * https://dockerhub.yonyougov.top/api/v2.0/projects/crux/repositories
     */
    public List<HarborRepositories> getRepositories(String projectName, Integer page, Integer pageSize) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setBasicAuth(harborInfo.getUsername(),harborInfo.getPassword());
        HttpEntity httpEntity = new HttpEntity(httpHeaders);
        String url = harborInfo.getUrl() + "projects/" + projectName + "/repositories?page="+page + "&page_size=" + pageSize;
        log.debug("获取项目下的镜像仓库的请求路径为: {}",url);
        ResponseEntity<List<HarborRepositories>> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, new ParameterizedTypeReference<List<HarborRepositories>>() {
        });
        if(responseEntity.getStatusCode().value() == 200 && responseEntity.hasBody()){
            return responseEntity.getBody();
        }
        return null;
    }

    public List<HarborRepositories> getRepositoriesByName(String projectName, String repository, Integer page, Integer pageSize) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setBasicAuth(harborInfo.getUsername(),harborInfo.getPassword());
        HttpEntity httpEntity = new HttpEntity(httpHeaders);
        String url = harborInfo.getUrl() + "projects/" + projectName + "/repositories?page="+page + "&page_size=" + pageSize + "&q=name="+projectName+"/"+repository;
        log.debug("获取项目下的镜像仓库的请求路径为: {}",url);
        ResponseEntity<List<HarborRepositories>> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, new ParameterizedTypeReference<List<HarborRepositories>>() {
        });
        if(responseEntity.getStatusCode().value() == 200 && responseEntity.hasBody()){
            return responseEntity.getBody();
        }
        return null;
    }
}
